package com.srwl.mytx.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSONObject;
import com.bumptech.glide.Glide;
import com.srwl.mytx.Constant;
import com.srwl.mytx.Helper;
import com.srwl.mytx.domain.User;
import com.srwl.mytx.R;
import com.srwl.mytx.RetrofitManager;
import com.srwl.mytx.adapter.MultipleCouponReceiverItemAdapter;
import com.srwl.mytx.domain.CommonResult;
import com.srwl.mytx.domain.Coupon;
import com.srwl.mytx.parse.UserProfileManager;
import com.srwl.mytx.service.CouponService;
import com.srwl.mytx.utils.DateUtils;
import com.srwl.mytx.utils.GlideLoadUtils;
import com.srwl.mytx.utils.Utils;
import com.srwl.mytx.widget.NodataFooter;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import me.dkzwm.widget.srl.MaterialSmoothRefreshLayout;
import me.dkzwm.widget.srl.SmoothRefreshLayout;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class MultipleCouponDetailActivity extends BaseActivity {
    public static void startActivity(Context context, Coupon coupon) {
        context.startActivity(new Intent(context, MultipleCouponDetailActivity.class).putExtra(Constant.EXTRA_INFO_COUPON, coupon));
    }

    private static final String TAG = "MultipleCouponDetailAct";
    private Coupon parentCoupon;
    private Coupon childCoupon;
    private User targetUser;
    private ArrayList<Coupon> couponList = new ArrayList<>();
    private MultipleCouponReceiverItemAdapter mAdapter;

    private TextView tvUserName;
    private TextView tvGreeting;
    private TextView tvMoneyAmount;
    private TextView tvMoneyStatus;
    private ImageView ivAvatar;
    private TextView tvMoneyUse;
    private ImageView ivGroupIcon;
    private ProgressBar progressBar;
    private MaterialSmoothRefreshLayout refreshLayout;
    private int page = 1;
    private boolean hasNextPage;
    private String parentCouponId;
    private Toolbar toolbar;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.fragment_multiple_coupon_detail_layout);
        initViewsAndEvents();
    }

    protected void initViewsAndEvents() {
        //   StatusBarCompat.setStatusBarColorForCollapsingToolbar(this, appBarLayout, collapsingToolbarLayout, toolbar, getResources().getColor(R.color.rp_top_red_color));
        parentCoupon = getIntent().getParcelableExtra(Constant.EXTRA_INFO_COUPON);
        childCoupon = getIntent().getParcelableExtra(Constant.EXTRA_INFO_CHILD_COUPON);
        if (parentCoupon != null) {
            targetUser = parentCoupon.getTargetUser();
            parentCouponId = parentCoupon.getId();
        } else if (childCoupon != null) {
            targetUser = childCoupon.getTargetUser();
            parentCouponId = childCoupon.getParentId();
        }


        RecyclerView recyclerView = findViewById(R.id.money_detail_list);
        recyclerView.setHasFixedSize(true);
        LinearLayoutManager mLayoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(mLayoutManager);
        mAdapter = new MultipleCouponReceiverItemAdapter(this, couponList);

        recyclerView.setAdapter(mAdapter);


        initView();
        //setHeaderViews();
        initRefreshLayout();
        loadData(true, false);
    }

    protected void setStatusDark() {
        Window window = getWindow();
        window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
        window.setStatusBarColor(getResources().getColor(R.color.rp_top_red_color));
    }

    private void initView() {
        toolbar = findViewById(R.id.toolbar);
        toolbar.setNavigationOnClickListener(v -> finish());

        tvUserName = findViewById(R.id.tv_money_sender);
        tvGreeting = findViewById(R.id.tv_greeting);
        tvMoneyStatus = findViewById(R.id.tv_money_status);
        tvMoneyAmount = findViewById(R.id.tv_money_amount);
        ivAvatar = findViewById(R.id.iv_avatar);
        tvMoneyUse = findViewById(R.id.tv_money_use);
        ivGroupIcon = findViewById(R.id.iv_group_random);
        progressBar = findViewById(R.id.progress_bar);
        refreshLayout = findViewById(R.id.refresh_layout);
        if (targetUser != null) {
            tvUserName.setText(targetUser.getUsername());
            //Glide.with(this).load(targetUser.getAvatar()).error(R.drawable.tx_default_avatar).into(ivAvatar);
            GlideLoadUtils.glideLoad(this, targetUser.getAvatar(), ivAvatar, R.drawable.tx_default_avatar_1);
        }
    }

    private void initRefreshLayout() {
        refreshLayout.setNestedScrollingEnabled(false);
        refreshLayout.setDisableRefresh(false);
        refreshLayout.setDisableLoadMore(false);
        refreshLayout.setEnableOverScroll(false);
        refreshLayout.setOnRefreshListener(new SmoothRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefreshing() {
                page = 1;
                loadData(false, true);
            }

            @Override
            public void onLoadingMore() {
                if (hasNextPage) {
                    loadData(false, false);
                } else {
                    refreshLayout.refreshComplete();
                }
            }

        });
    }

    private void loadData(boolean isFirst, boolean isRefresh) {

        if (!Helper.getInstance().isNetworkConnected()) {
            if (!isFirst) refreshLayout.refreshComplete();
            showToast_v1(getString(R.string.network_anomalies));
            return;
        }
        if (parentCouponId == null) {
            return;
        }
        Map<String, Object> body = new HashMap<>();
        body.put("page", page);
        body.put("size", 10);
        body.put("couponId", parentCouponId);
        if (isFirst) {
            progressBar.setVisibility(View.VISIBLE);
        }
        RetrofitManager.getInstance().createRequest(CouponService.class)
                .getMultipleCouponReceivedRecord(body)
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        if (isFirst) {
                            progressBar.setVisibility(View.GONE);
                        } else {
                            refreshLayout.refreshComplete();
                        }
                        CommonResult result = response.body();
                        if (!response.isSuccessful() || result == null) {
                            Log.e(TAG, "获取红包记录出错：" + response.message());
                            showToast(getString(R.string.system_busy));
                            if (page == 1) {
                                mAdapter.showErrorView();
                            }
                            return;
                        }

                        if (result.isError()) {
                            Log.e(TAG, "获取红包记录出错：" + result.getMsg());
                            showToast(getString(R.string.system_busy));
                            if (page == 1) {
                                mAdapter.showErrorView();
                            }
                            return;
                        }

                        JSONObject resultData = (JSONObject) result.getData();
                        if (page == 1 && resultData.containsKey("parentCoupon")) {
                            parentCoupon = resultData.getObject("parentCoupon", Coupon.class);
                            setHeaderViews();
                        }
                        JSONObject pageInfo = resultData.getJSONObject("pageInfo");
                        Log.d(TAG, "onResponse: " + pageInfo.toString());
                        pageInfo.getInteger("total");
                        hasNextPage = pageInfo.getBoolean("hasNextPage");
                        if (!hasNextPage) {
                            refreshLayout.postDelayed(() -> refreshLayout.setFooterView(new NodataFooter(MultipleCouponDetailActivity.this)), 2000);
                        }
                        List<Coupon> coupons = pageInfo.getJSONArray("list").toJavaList(Coupon.class);

                        if (coupons.size() != 0) {
                            if (isRefresh) {//如果是刷新，需要先清除原始数据
                                couponList.clear();
                            }
                            couponList.addAll(coupons);
                            mAdapter.showNormalView();
                            page++;
                        } else if (page == 1) {
                            mAdapter.showNoDataView();
                        }


                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        if (isFirst) {
                            progressBar.setVisibility(View.GONE);
                        } else {
                            refreshLayout.refreshComplete();
                        }
                        if (page == 1) {
                            mAdapter.showErrorView();
                        }
                        Log.e(TAG, "onFailure: " + t.getMessage());
                    }
                });


    }

    private void setHeaderViews() {


        tvGreeting.setText(parentCoupon.getGreeting());

        tvMoneyAmount.setVisibility(View.VISIBLE);
        tvMoneyAmount.setText(String.format("￥%s", Utils.moneyFormat(parentCoupon.getAmount())));
        if (childCoupon != null) {
            tvMoneyUse.setVisibility(View.VISIBLE);
            tvMoneyUse.setText("你抢到 ￥" + childCoupon.getAmount() + "，已存入账户余额");
        } else {
            tvMoneyUse.setVisibility(View.INVISIBLE);
        }

        switch (parentCoupon.getType()) {
            case Constant.COUPON_TYPE_MULTIPLE_RANDOM:
                ivGroupIcon.setVisibility(View.VISIBLE);
                ivGroupIcon.setBackgroundResource(R.drawable.rp_random_icon);
                break;
//            case Constant.RED_PACKET_TYPE_GROUP_EXCLUSIVE:
//                ivGroupIcon.setVisibility(View.VISIBLE);
//                ivGroupIcon.setBackgroundResource(R.drawable.rp_exclusive_icon);
//                break;
            default:
                ivGroupIcon.setVisibility(View.GONE);
                break;
        }
        boolean isMyCoupon = TextUtils.equals(UserProfileManager.getInstance().getLoginUserInfo().getuId(), targetUser.getuId());
        String redPacketStatus = "";
        Integer receivedCount = parentCoupon.getReceivedCount();


        switch (parentCoupon.getStatus()) {
            case Constant.COUPON_STATUS_RECEIVABLE:
                if (isMyCoupon) {
                    redPacketStatus = String.format(getString(R.string.group_money_available_sender), Utils.numberFormat(receivedCount), Utils.numberFormat(parentCoupon.getTotalCount() - receivedCount), Utils.moneyFormat(parentCoupon.getBalance()));
                } else {
                    redPacketStatus = String.format(getString(R.string.group_money_available_receiver), Utils.numberFormat(receivedCount), Utils.numberFormat(parentCoupon.getTotalCount() - receivedCount));
                }
                break;
            case Constant.COUPON_STATUS_REMAIN_ZERO:
                redPacketStatus = String.format(getString(R.string.group_money_unavailable_rand_sender), parentCoupon.getTotalCount() + "", DateUtils.getTimeSpanWithMillis(parentCoupon.getCreated(), parentCoupon.getUpdated()));
//                if (parentCoupon.getType() == Constant.COUPON_TYPE_MULTIPLE_RANDOM) {
//                    redPacketStatus = String.format(getString(R.string.group_money_unavailable_rand_sender), parentCoupon.getTotalCount() + "", DateUtil.getTimeSpanWithMillis(parentCoupon.getCreated(), parentCoupon.getUpdated()));
//                    if (isMyCoupon) {
//                    } else {
//                        redPacketStatus = String.format(getString(R.string.group_money_unavailable_rand_receiver), parentCoupon.getTotalCount() + "", DateUtil.getTimeSpanWithMillis(parentCoupon.getCreated(), parentCoupon.getUpdated()));
//                    }
//                } else {
//                    if (isMyCoupon) {
//                        redPacketStatus = String.format(getString(R.string.group_money_unavailable_avg_sender), parentCoupon.getTotalCount() + "", Utils.moneyFormat(parentCoupon.getAmount()));
//                    } else {
//                        redPacketStatus = String.format(getString(R.string.group_money_unavailable_avg_receiver), parentCoupon.getTotalCount() + "");
//                    }
//                }
                break;
            case Constant.COUPON_STATUS_EXPIRED:
                if (isMyCoupon) {
                    tvMoneyUse.setVisibility(View.VISIBLE);
                    tvMoneyUse.setText(String.format("剩余%s元已返回账户余额", Utils.moneyFormat(parentCoupon.getBalance())));
                }
                redPacketStatus = String.format(getString(R.string.group_money_expired), receivedCount + "", parentCoupon.getTotalCount() - receivedCount + "", Utils.moneyFormat(parentCoupon.getBalance()));
                break;
        }
        tvMoneyStatus.setText(redPacketStatus);
    }


}
